//
//  ViewController.m
//  MultiLevelDepartmentDemo
//
//  Created by Gin on 2021/6/7.
//

#import "ViewController.h"
#import "NRBreadcrumView.h"
#import "NRDesignateDeptCell.h"
#import "NRDesignateGroupModel.h"
#import "NRDesignateChoiceTableHeaderView.h"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource,NRBreadcrumViewDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NRBreadcrumView *breadcrumView;
@property(nonatomic, strong) NSMutableArray *breadcrumArray;
@property(nonatomic, strong) NSMutableArray *groupChangedArray;
@property(nonatomic, strong) NRDesignateGroupModel *groupTree;

@property(nonatomic, strong) NRDesignateChoiceTableHeaderView *allSelectView;
///当前树节点
@property (nonatomic, strong, readwrite) NRDesignateGroupModel *currentGroupNodeModel;
///是否第一级的全选（0 没有全选  1全选  2手动点击了取消全选）
@property(nonatomic, assign) CGFloat allFlag;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"部门选择树";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"提交结果" style:UIBarButtonItemStylePlain target:self action:@selector(submitResultAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.breadcrumView];
    [self.view addSubview:self.tableView];
    
     [self updateBreadcrumWithGroupData:self.groupTree];
    // Do any additional setup after loading the view.
}

- (void)submitResultAction{
    [self.groupChangedArray removeAllObjects];
    [self traversalGroupNode:self.groupTree];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:self.allFlag == 1 ? @"全选了" : @"没有全选" message:[NSString stringWithFormat:@"%@",self.groupChangedArray] preferredStyle:UIAlertControllerStyleAlert];
    //2.2 取消按钮
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消按钮");
    }];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)traversalGroupNode:(NRDesignateGroupModel *)groupNode{
    ///第一个循环找出被选中的
    if(groupNode.checked){
        if(groupNode.departmentId){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            dict[@"departmentId"] = groupNode.departmentId;
            dict[@"checked"] = @"1";
            dict[@"name"] = groupNode.name;
            [self.groupChangedArray addObject:dict];
        }else{
            self.allFlag = 1;
        }
        return;
    }
    ///第一个循环找出之前被选中然后被其他代码取消选中的
    if(groupNode.codeChanged){
        if(groupNode.departmentId){
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            dict[@"departmentId"] = groupNode.departmentId;
            dict[@"checked"] = @"0";
            dict[@"name"] = groupNode.name;
            [self.groupChangedArray addObject:dict];
        }else{
            self.allFlag = 2;
        }
    }
    for(NRDesignateGroupModel *model in groupNode.groups){
        [self traversalGroupNode:model];
    }
}


- (void)updateBreadcrumWithGroupData:(NRDesignateGroupModel *)groupModel{
    [self.breadcrumArray addObject:groupModel];
    self.breadcrumView.breadcrumArray = self.breadcrumArray;
    [self updateCurrentGroupModel:groupModel];
}

- (void)updateCurrentGroupModel:(NRDesignateGroupModel *)groupModel{
    self.currentGroupNodeModel = groupModel;
    self.allSelectView.checked = groupModel.checked;
    [self getDepartmentGroupData:groupModel];
}

- (void)getDepartmentGroupData:(NRDesignateGroupModel *)groupModel{
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    if(groupModel.groups.count > 0){
        ///已经加载入内存了
        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        [self.tableView.tableHeaderView addSubview:self.allSelectView];
        self.allSelectView.checked = groupModel.checked;
        [self.tableView reloadData];
    }else{
        ///这里是从本地拿取，或者从服务端拿取
        NSMutableArray *groupArray = [[NSMutableArray alloc] init];
        for(int i = 0; i < 10; i++){
            NRDesignateGroupModel *model = [[NRDesignateGroupModel alloc] init];
            model.departmentId = [NSString stringWithFormat:@"%@%d",groupModel.departmentId,i];
            model.name = [NSString stringWithFormat:@"%@-部门%d",groupModel.name,i];
            model.parentGroupModel = groupModel;
            [groupArray addObject:model];
        }
        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        [self.tableView.tableHeaderView addSubview:self.allSelectView];
        [self changedGroupModelCheckStatusWithGroupData:groupArray withGroupModel:groupModel];
    }
}



- (void)changedGroupModelCheckStatusWithGroupData:(NSArray *)groupData withGroupModel:(NRDesignateGroupModel *)groupModel{
    if(groupModel.codeChanged){
        for(NRDesignateGroupModel *model in groupData){
            model.checked = groupModel.checked;
            model.codeChanged = YES;
        }
        groupModel.groups = groupData;
        [self.tableView reloadData];
    }else{
        BOOL flag = YES;
        if(groupData.count > 0){
            for(int i = 0; i < groupData.count; i++){
                NRDesignateGroupModel *dataModel = [groupData objectAtIndex:i];
                if(dataModel.checked == NO){
                    flag = NO;
                }
            }
        }
        groupModel.checked = flag;
        groupModel.groups = groupData;
        self.allSelectView.checked = groupModel.checked;
        [self.tableView reloadData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.currentGroupNodeModel.groups.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NRDesignateDeptCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRDesignateDeptCell" forIndexPath:indexPath];
    NRDesignateGroupModel *model = [self.currentGroupNodeModel.groups objectAtIndex:indexPath.row];
    cell.name = model.name;
    cell.checked = model.checked;
    cell.showChoiceButton = YES;
    cell.showArrowButton = YES;
    @weakify(self)
    cell.choiceBlock = ^{
        @strongify(self)
        [self selectedOnceBtn:indexPath];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NRDesignateGroupModel *model = [self.currentGroupNodeModel.groups objectAtIndex:indexPath.row];
    [self updateBreadcrumWithGroupData:model];
}

- (void)selectedOnceBtn:(NSIndexPath *)indexPath{
    NRDesignateGroupModel *groupModel = [self.currentGroupNodeModel.groups objectAtIndex:indexPath.row];
    [groupModel updateChecked:!groupModel.checked];
    self.allSelectView.checked = self.currentGroupNodeModel.checked;
}

- (void)selectedAllBtn{
    [self.currentGroupNodeModel updateChecked:!self.currentGroupNodeModel.checked];
    [self.tableView reloadData];
}

#pragma mark - NRBreadcrumViewDelegate
-(void)breadcrumViewDidSelectedGroupModel:(NRDesignateGroupModel *)groupModel{
    if(![self.currentGroupNodeModel.departmentId isEqualToString:groupModel.departmentId]){
        NSInteger index = [self.breadcrumArray indexOfObject:groupModel];
        NSArray *array = [self.breadcrumArray subarrayWithRange:NSMakeRange(0, index+1)];
        self.breadcrumArray = [NSMutableArray arrayWithArray:array];
        self.breadcrumView.breadcrumArray = array;
        [self updateCurrentGroupModel:groupModel];
    }
}

- (NRBreadcrumView *)breadcrumView{
    if(!_breadcrumView){
        _breadcrumView = [[NRBreadcrumView alloc] initWithFrame:CGRectMake(0, 88, self.view.frame.size.width, 42)];
        _breadcrumView.viewDelegate = self;
    }
    return _breadcrumView;
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.breadcrumView.bottom + 20, self.view.frame.size.width, self.view.frame.size.height - self.breadcrumView.bottom - 20)];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerNib:[UINib nibWithNibName:@"NRDesignateDeptCell" bundle:nil] forCellReuseIdentifier:@"NRDesignateDeptCell"];
    }
    return _tableView;
}

- (NRDesignateChoiceTableHeaderView *)allSelectView{
    if(!_allSelectView){
        _allSelectView = [[[NSBundle mainBundle] loadNibNamed:@"NRDesignateChoiceTableHeaderView" owner:self options:nil] lastObject];
        _allSelectView.width = kScreenWidth;
        _allSelectView.height = 50;
        _allSelectView.checked = NO;
        @weakify(self)
        _allSelectView.choiceBlock = ^{
            @strongify(self)
            [self selectedAllBtn];
        };
    }
    return _allSelectView;
}

- (NRDesignateGroupModel *)currentGroupNodeModel{
    if(!_currentGroupNodeModel){
        _currentGroupNodeModel = [[NRDesignateGroupModel alloc] init];
    }
    return _currentGroupNodeModel;
}

- (NRDesignateGroupModel *)groupTree{
    if(!_groupTree){
        _groupTree = [[NRDesignateGroupModel alloc] init];
        _groupTree.name = @"全部";
    }
    return _groupTree;
}

- (NSMutableArray *)breadcrumArray{
    if(!_breadcrumArray){
        _breadcrumArray = [[NSMutableArray alloc] init];
    }
    return _breadcrumArray;
}

- (NSMutableArray *)groupChangedArray{
    if(!_groupChangedArray){
        _groupChangedArray = [[NSMutableArray alloc] init];
    }
    return _groupChangedArray;
}

@end
